package org.summerframework.core.util;

import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;

public class Base64Util {

    public static final String DEFAULT_ENCODING = "UTF-8";

    public static String encode(String value, String encoding) {
        byte[] data;
        try {
            data = value.getBytes(encoding);
            return encode(data);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Unsupported Encoding Exception");
        }
    }

    public static String encode(String value) {
        return encode(value, DEFAULT_ENCODING);
    }

    public static String encode(byte[] data) {
        return Base64.encodeBase64String(data);
    }

    public static String encodeWithURLSafeString(byte[] data) {
        return Base64.encodeBase64URLSafeString(data);
    }

    public static byte[] decodeAsByte(String value) {
        return Base64.decodeBase64(value);
    }

    public static String decode(String value, String encoding) {
        try {
            byte[] data = decodeAsByte(value);
            return new String(data, encoding);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Unsupported Encoding Exception");
        }
    }

    public static String decode(String value) {
        return decode(value, DEFAULT_ENCODING);
    }
}
